import { ref } from 'vue';
import { defineStore } from 'pinia';

const components = import.meta.glob('@/view/**/*.vue');
const baseRoutes = [{
  name: 'layout',
  path: '/layout/index',
  text: 'layout',
  children: [{
    id: 'trade',
    name: 'trade',
    path: '/stock/trade',
    text: '持仓详情',
    url: '/stockPosition/queryPage',
  }, {
    id: 'money',
    name: 'money',
    path: '/stock/money',
    text: '资金总览'
  }]
}, {
  name: 'notfound',
  path: '/:pathMatch(.*)',
  href: '/error/404',
  text: '错误',
  hidden: true
}];

const getComponent = async(compName, path) => {
  const keys = Object.keys(components);
  const matchKeys = keys.filter((key) => {
    const k = key.replace('/src/view', '')
      .replace('/src', '')
      .replace('.vue', '');
    return k === path;
  });

  const component = components[matchKeys[0]];
  return !component ? null : await component().then(comp => ({
    ...comp.default,
    name: compName
  }));
};

const formatRoute = async(routes, routeMap, routerList) => {
  for (let item of routes) {
    item.name = item.name || item.id;
    item.meta = item.meta || {};
    item.meta.keepAlive = (typeof item.keepAlive !== 'undefined')
      ? item.keepAlive : ((typeof item.meta.keepAlive === 'undefined') ? true : item.meta.keepAlive);
    item.meta.url = item.url;
    item.meta.title = item.text;
    item.meta.buttons = item.buttons;
    item.meta.hidden = item.hidden;
    if (item.href || item.path) {
      item.component = await getComponent(item.name, item.href || item.path);
    }

    if (item.meta && item.meta.url) {
      routeMap[item.id] = item;
    }

    if (item.children && item.children.length > 0) {
      await formatRoute(item.children, routeMap, routerList);

      if ((item.children || []).length === 0 && item.hidden !== true) {
        routerList.push({ label: item.text, value: item.id });
      }
    } else {
      if (item.hidden !== true && (item.href || item.path)) {
        routerList.push({ label: item.text, value: item.id });
      }
    }
  }
};

export const useRouterStore = defineStore('router', () => {
  const routes = ref([]);
  const routeMap = ({});
  const routerList = ref([]);
  const isInit = ref(false);

  const initRouter = async(router) => {
    if (isInit.value) {
      return false;
    }

    await formatRoute(baseRoutes, routeMap, routerList.value);
    baseRoutes.forEach(route => router.addRoute(route));
    routes.value = baseRoutes;
    isInit.value = true;
    return true;
  };

  return {
    routes,
    routeMap,
    routerList,
    initRouter
  };
});

